package com.kyb.cms.config.interceptor;

import com.kyb.cms.util.GlobalConstant;
import com.kyb.cms.util.LoginCookieUtil;
import com.kyb.cms.util.LoginUser;
import com.kyb.cms.util.ThreadUser;
import lombok.extern.slf4j.Slf4j;
import org.armada.galileo.annotation.mvc.NoToken;
import org.armada.galileo.common.util.JsonUtil;
import org.armada.galileo.exception.BizException;
import org.armada.galileo.exception.LoginTimeoutException;
import org.armada.galileo.mvc_plus.encrypt.EncryptUtil;
import org.armada.galileo.mvc_plus.support.MiniWebxServlet;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author xiaobo
 * @date 2022/12/13 10:49
 */

@Slf4j
public class LoginStatusInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        Method method = (Method) request.getAttribute(MiniWebxServlet.SPRING_CONTROLLER_INVOKE_METHOD);
        if (method == null) {
            return true;
        }
        String cookieValue = LoginCookieUtil.getCookie(GlobalConstant.Agent_User_Login_Cookie_Head, request);

        LoginUser u = null;

        if (cookieValue != null) {
            try {
                u = JsonUtil.fromJson(cookieValue, LoginUser.class);
            } catch (Exception e) {
                throw new LoginTimeoutException();
            }
        }

        boolean noTokenUrl = method.isAnnotationPresent(NoToken.class) || method.getDeclaringClass().isAnnotationPresent(NoToken.class);

        if (u == null && !noTokenUrl) {
            throw new LoginTimeoutException();
        }

        ThreadUser.set(u);

        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ThreadUser.remove();
    }


}
